/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.agentslab.resourceprovider;

import aa.core.Actor;
import aa.core.ActorName;
import aa.core.CommunicationException;
import aa.core.Contract;
import aa.tool.CyberOrgTuple;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author mehadihasan
 */
public class ResourceProvider extends Actor {

    ActorName resourceBroker = new ActorName("10.225.160.74", 5);
    Contract contract = null;

    public ResourceProvider() {
        this.contract = new Contract(10000, 100, 1);
    }

    public Contract getContract() {
        return contract;
    }

    public void setContract(Contract contract) {
        this.contract = contract;
    }

//    public void register(Contract contract) {
//        this.setContract(contract);
//        CyberOrgTuple[] tupleList = null;
//        try {
//            tupleList = (CyberOrgTuple[]) call(resourceBroker, "getPotentialResourceList", this.getContract());
//            if (tupleList == null) {
//                System.err.println("no potential resource found...please try again later...");
//            } else {
//                for (CyberOrgTuple cyberOrgTuple : tupleList) {
//                    if(!negotiate(cyberOrgTuple)){
//                        System.err.println("you can not run a game server being so cheap...");
//                    }
//                }
//            }
//
//        } catch (CommunicationException ex) {
//            ex.printStackTrace();
//        }
//    }

    public boolean negotiate(CyberOrgTuple cyberOrgTuple) {

        Contract finalContract = null;

        try {
            ActorName remoteFaci = new ActorName(cyberOrgTuple.getDestination(), cyberOrgTuple.getId());
            finalContract = (Contract) call(remoteFaci, "negotiate", this.getActorName(), this.getContract());
            if (finalContract != null) {
                System.out.println("negotiation successful... final contract: " + finalContract);
                cyberOrgTuple.setContract(finalContract);
                registerCDM(cyberOrgTuple);
                return true;
            } else {
                System.err.println("failed negotiation");
                return false;
            }
        } catch (CommunicationException ex) {
            ex.printStackTrace();
            return false;
        }

    }

    public void registerCDM(CyberOrgTuple cyberOrgTuple) {
        send(resourceBroker, "registerToCDM", cyberOrgTuple);
        System.out.println("CyberOrg " + cyberOrgTuple + " successfully registered to CDM...");
    }

  
}
